package chapter14;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/22 18:48
 */
public class SerializableTest {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(new Student[]{
                new Student("张三", 18, 89.87),
                new Student("李四", 17, 90.1)
        });

//        writeStudents(students,"D:\\students.dat");
//
//        List<Student> list = readStudents("D:\\students.dat");
        writeStudentsAll(students, "D:\\students.dat");
        List<Student> list = readStudentsAll("D:\\students.dat");

        list.forEach(System.out::println);
    }

    private static List<Student> readStudents(String fileName) {
        List<Student> students = new ArrayList<>();
        try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)))) {
            int size = in.readInt();
            for (int i = 0; i < size; i++) {
                Student student = (Student) in.readObject();
                students.add(student);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return students;
    }

    private static void writeStudents(final List<Student> students, String fileName) {
        try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))) {
            out.writeInt(students.size());
            for (Student student : students) {
                out.writeObject(student);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeStudentsAll(final List<Student> students, String fileName) {
        try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))) {
            out.writeObject(students);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<Student> readStudentsAll(String fileName) {
        List<Student> students = new ArrayList<>();
        try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)))) {
            students = (List<Student>) in.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return students;
    }
}
